#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年4月17日

@author: Administrator
'''

from django.core.cache import cache

from message import settings
from message.models import Message

def make_user_messages_cache_key(user_id, prefix=settings.USER_MESSAGES_CACHE_KEY_PREFIX):
    '''
    根据参数生成cache key
    '''
    return '%s.%s' % (prefix, user_id)

def get_user_messages_cache(user_id):
    '''
    从cache中获取用户未读消息数
    '''
    return cache.get(make_user_messages_cache_key(user_id))

def set_user_messages_cache(user_id, value, timeout=settings.USER_MESSAGES_CACHE_TIMEOUT):
    '''
    设置用户未读消息数cache
    '''
    cache.set(make_user_messages_cache_key(user_id), value, timeout)
    
def update_user_message_cache(user_id):
    message = get_user_messages_cache(user_id)
    if message:
        set_user_messages_cache(user_id, get_user_messages_db(user_id))
        
def add_user_message_cache(user_id):
    message = get_user_messages_cache(user_id)
    if message:
        message['total_count'] += 1
        message['letter_count'] += 1
        set_user_messages_cache(user_id, get_user_messages_db(user_id))
        
def reduce_user_message_cache(user_id, num=1):
    message = get_user_messages_cache(user_id)
    if message:
        message['total_count'] = max(0, message['total_count'] - num)
        message['letter_count'] = max(0, message['letter_count'] - num)
        set_user_messages_cache(user_id, get_user_messages_db(user_id))

def delete_user_messages_cache(user_id):
    '''
    删除用户未读消息数cache
    '''
    cache.delete(make_user_messages_cache_key(user_id))

def get_user_messages_db(user_id):
    '''获取用户消息统计'''
    total_count = Message.objects.filter(recv_user_id=user_id, state=0, readed=False).count()
    letter_count = Message.objects.filter(recv_user_id=user_id, state=0, category=1, readed=False).count()

    data = {
        'total_count':total_count,
        'letter_count':letter_count
    }

    return data

def get_user_messages(user_id, use_cache=True):
    '''
    获取用户未读消息数  cache->db->cache
    no: 编号
    use_cache: True/False   True-优先查询缓存 False-优先查询数据库
    '''
    if use_cache:
        detail = get_user_messages_cache(user_id)
    else:
        detail = None
    if detail != None and isinstance(detail, dict):
        return detail
    detail = get_user_messages_db(user_id)
    set_user_messages_cache(user_id, detail)
    return detail
